import { Link, useLocation, useNavigate } from 'react-router-dom'
import './index.less'
import { Breadcrumb } from 'antd'
import { routers } from '@/router'
import { useEffect, useState } from 'react'
const BreadCrumb = () => {
  const navigate = useNavigate()
  const [routesInfo, setRoutesInfo] = useState<IRoutesType[]>([])
  const pathname = useLocation().pathname
  useEffect(() => {
    const firstRoute = routers?.find((item: IRoutesType) => item.fullPath === pathname)
    if (firstRoute?.path) {
      setRoutesInfo([firstRoute])
    } else {
      const firstPath = pathname.slice(1).split('/')[0]
      const otherPath = pathname.slice(firstPath.length + 2)
      if (otherPath.length !== 0) {
        const firstRoute = routers?.find((item: any) => item.path === firstPath)
        if (Array.isArray(firstRoute?.children)) {
          const secondRoute = firstRoute?.children.find((it: any) => it.path === otherPath)
          if (firstRoute?.path && secondRoute?.path) setRoutesInfo([firstRoute, secondRoute])
        }
      }
    }
  }, [pathname])
  const getItems = () => {
    return routesInfo.map((item: any, index: number) => {
      return {
        title: (
          <span
            className={'bread_crumb_base_text ' + (index === routesInfo.length - 1 ? 'bread_crumb_base_text_bold' : '')}
            onClick={() => {
              if (!item.resourcePath) return
              navigate(item?.fullPath)
            }}
          >
            {item?.name}
          </span>
        ),
        key: item?.fullPath,
      }
    })
  }
  const items = [
    {
      title: (
        <Link className="bread_crumb_base_text" to={'/'}>
          首页
        </Link>
      ),
      key: '',
    },
  ].concat(getItems())
  return (
    <div className="base_layout_breadcrumb">
      <Breadcrumb items={items}></Breadcrumb>
    </div>
  )
}

export default BreadCrumb
